const express = require('express');
//引入连接池模块
const pool = require('../pool.js');
//创建路由器对象
const r = express.Router();
r.delete("/del_cart/:pid&:button",(req,res)=>{
	let _pid=req.params.pid;
	let _button=req.params.button;
	//查询数据库商品的数量
	let stop=false;
	pool.query('select count from shoppingcart_item where product_id=?',[_pid],(err,result)=>{
		if(err) throw err;
		if(result.length==0){
			stop=true;
		};
		if(stop) return; //跳出整个函数
		let _count=result[0].count //获取购物车商品数量的值
		if(_button==1){
			//如果button的值等于1，商品数量+1
			pool.query('update shoppingcart_item set count=count+1 where product_id=?',[_pid],(err,result)=>{
				if(err) throw err;
				if(result.affectedRows>0){
					res.send("1");
				}
			});
		}else if(_button==-1){
		//如果button的值等于-1，商品数量-1
		pool.query('update shoppingcart_item set count=count-1 where product_id=?', [_pid], (err, result) => {
			if (err) throw err;
			_count--;//商品数量的值-1  删除后计算最终商品的数量，如果为0，进行删除购物车商品操作
			if(!_count){
				pool.query('delete from shoppingcart_item where product_id=?',[_pid],(err,result)=>{
					if(err) throw err;
					if(res.affectedRows>0){
						res.send('1');
					}else{
						res.send("0")
					}
				})
			}
		});
		}
	});
});

r.get('/search_item/',(req,res)=>{
	// let _userid=req.params.user_id;
	//三表查询：商品表（名称，价格，标题）,购物车表（数量，规格）,图标（小图）
	sql=`select a.name,a.title,a.price,a.pid,
		b.product_id,b.count,b.meals_num,b.user_id,
		c.product_id,c.sm from
		product a,shoppingcart_item b,product_pic c where 
		a.pid=b.product_id and a.pid=c.product_id`;      //and b.user_id=?后期完善登录验证
	pool.query(sql,(err,result)=>{//[_userid],
		if(err) throw err;
		if(result.length>0){
			res.send(result);
		}
	});
});

//导出路由器对象
module.exports = r;
